package com.example.demo.task;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.time.LocalDateTime;

/**
 * 定时任务(方式一)
 * @program: MyBatisGenerator
 * @author: daPangDong
 * @create: 2022-06-16 10:39
 */
//@Configuration
public class ScheduledTask implements SchedulingConfigurer {

    @Mapper
    public interface TaskMapper{
        @Select("select cron from cron where cron_id=#{id}")
        String getCron(Long id);
    }

    @Autowired
    @SuppressWarnings("all")
    TaskMapper taskMapper;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> {
                    System.out.println("执行定时任务: " + LocalDateTime.now().toLocalTime());
                },
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 从数据库获取执行周期
                    String cron = taskMapper.getCron(1L);
                    //2.2 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }
}